package com.atguigu.gulimall.auth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.common.utils.HttpUtils;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberResponseVo;
import com.atguigu.gulimall.auth.entity.vo.SocialUser;
import com.atguigu.gulimall.auth.feign.MemberFeignService;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * 处理社交请求
 *
 * @Author 胡菜鸡
 * @Create 2022-02-07-10:07
 */
@Slf4j
@Controller
public class OAuth2Controller {

    @Autowired
    MemberFeignService memberFeignService;

    @GetMapping("/oauth2.0/weibo/success")
    public String weibo(@RequestParam("code") String code, HttpSession session) throws Exception {
        //根据code换取access_token
        Map<String, String> map = new HashMap<>();
        map.put("client_id", "3581217165");
        map.put("client_secret", "9c502d0f1ccffbd9aa47349918d97db7");
        map.put("grant_type", "authorization_code");
        map.put("redirect_uri", "http://auth.gulimall.com/oauth2.0/weibo/success");
        map.put("code", code);
        HttpResponse response = HttpUtils.doPost("https://api.weibo.com", "/oauth2/access_token", "post", new HashMap<>(), map, new HashMap<>());

        //处理
        if (response.getStatusLine().getStatusCode() == 200) {
            //获取到了access_token
            String json = EntityUtils.toString(response.getEntity());
            SocialUser socialUser = JSON.parseObject(json, SocialUser.class);
            System.out.println(socialUser);

            /*
              知道当前是哪个社交用户
             */
            //1.如果用户是第一次进网站，自动注册进来（为当前社交用户生成一个会员信息账号，以后这个账号就对应此社交用户）
            //2.登录或者注册这个社交用户（通过uid判断是否第一次登录，是则进行注册并登录，否则直接登录）
            R r = memberFeignService.oAuthLogin(socialUser);
            if(r.getCode() == 0){
                //成功，跳转到首页
                MemberResponseVo data = r.getData(new TypeReference<MemberResponseVo>() {
                });
                log.info("登录成功：{}", data);

                //通过 spring-session 解决session在各个服务之间共享的问题
                /*
                    需要解决的问题（通过 GulimallSessionConfig配置类 解决）：
                        (1)默认作用域为当前服务，需要扩展到所有服务
                        (2)默认使用jbk序列化，需要改为json序列化
                 */
                session.setAttribute(AuthServerConstant.LOGIN_USER, data);
            } else {
                //失败，返回登录页
                return "redirect:http://auth.gulimall.com/login.html";
            }
        } else {
            //没有获取到access_token
            return "redirect:http://auth.gulimall.com/login.html";
        }

        System.out.println("登录成功");
        return "redirect:http://gulimall.com";
    }

}
